package cn.scxy.bookcity.service.impl;

import cn.scxy.bookcity.ex.ServiceException;
import cn.scxy.bookcity.mapper.UserRegMapper;
import cn.scxy.bookcity.pojo.dto.UserAddDTO;
import cn.scxy.bookcity.pojo.entity.User;
import cn.scxy.bookcity.service.IUserRegService;
import cn.scxy.bookcity.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserRegService implements IUserRegService {
    @Autowired
    UserRegMapper userRegMapper;

    @Override
    public void insert(UserAddDTO userAddDTO) {
        log.debug("开始处理注册用户业务,参数:{}",userAddDTO);
        if(!userAddDTO.getPhone().isEmpty()){
            int count = userRegMapper.countByPhone(userAddDTO.getPhone());
            if (count == 1) {
                String message = "手机号已被占用";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
            }
        }
        log.debug("即将向用户表插入数据,参数：{}",userAddDTO);
        User user = new User();
        BeanUtils.copyProperties(userAddDTO,user);
        int i = userRegMapper.insert(user);
        if(i==0){
            String message = "服务器繁忙,添加失败";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("添加成功");
    }
}
